import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.SynchronousQueue;

/**
 * 测试同步队列 只能一个任务入队，入队的同时会阻塞，直到任务被另一个线程取出
 * @author 管子
 * @date 2025/5/3 8:40
 * @description: TestSynchronousQueue 类
 */
@Slf4j
public class TestSynchronousQueue {

    public static void main(String[] args) {
        SynchronousQueue<Integer> integers = new SynchronousQueue<>();
        new Thread(() -> {
            try {
                log.info("putting {}", 1);
                integers.put(1);  // 在这里阻塞了，直到take被调用
                log.info("putted {}", 1);

                log.info("putting {}", 2);
                integers.put(2);
                log.info("putted {}", 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            try {
                log.info("taking {}", 1);
                integers.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();

    }

}
